package com.ebelter.btlibrary.btble.impl.ict;


import com.ebelter.btlibrary.btble.ble.bluetooth.device.impl.BleMessageAnalyser;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.impl.Channel;
import com.ebelter.btlibrary.btble.impl.ecg.callback.EcgResultCallback;
import com.ebelter.btlibrary.btble.impl.ict.callbcak.ErrorCallback;
import com.ebelter.btlibrary.btble.impl.ict.callbcak.IctResultCallback;
import com.ebelter.btlibrary.btble.impl.ict.model.IctError;
import com.ebelter.btlibrary.btble.impl.ict.model.IctCommand;
import com.ebelter.btlibrary.btble.impl.ict.model.IctResult;
import com.ebelter.btlibrary.util.ULog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 血压计数据解析器
 * Created by Sergio Pan on 2017/12/8.
 */

public class IctMessageAnalyser extends BleMessageAnalyser {

    private static final String TAG = "IctMessageAnalyser";

    private static IctMessageAnalyser instance = new IctMessageAnalyser();

    //数据解析后的各种回调
    private IctResultCallback measureResultCallback;
    private ErrorCallback mErrorCallback;
    /**** 上一次的测量时间，因设备无法停止发送数据，用于过滤重复数据 ***/
    private long preMeasureTime;

    private IctMessageAnalyser() {
//        recordSet.
    }


    public static IctMessageAnalyser getInstance() {
        return instance;
    }


    public void registerMeasureResultCallback(IctResultCallback callback) {
        this.measureResultCallback = callback;
    }

    public void registerErrorCallback(ErrorCallback callback) {
        this.mErrorCallback = callback;
    }


    /**
     * 解密数据
     *
     * @param data
     * @return
     */
    @Override
    protected byte[] decrypt(byte[] data) {
//        ULog.i(TAG, "-------decrypt--------data = " + getArrayString(data));
        //TODO 如若是加密数据，在此做解密处理,如若非加密数据，可不重写此方法

        return data;
    }

    /**
     * 开始解析
     *
     * @param data
     * @return
     */
    @Override
    protected void analyze(Channel channel, byte[] data) {
        ULog.i(TAG, "-------analyze----before filter----data = " + getArrayString(data));
        //解密后
//        if (data.length < 2 || data[0] != dataHeaderReceive || data.length != (data[1] & 0xff) + 3) {
//            return;
//        }
//        ULog.i(TAG, "-------analyze---after filter-----data = " + getArrayString(data));
        //业务码

        int cmdCode = data[0] & 0xff;

        switch (cmdCode) {
            case 0x20://动态数据
                onMeasuring(data);
            case 0x0c://在线测量结果
                doMeasureResult(data);
                break;
            case 0xbb://训练历史记录
//                doPracticeHistory(data);
                break;
            case 0xfe://测量结果历史记录
//                doHistoryResult(data);
                break;
            case 0xff://返回数据
                doOnFF(data);
                break;
        }


    }

    /**
     * 处理训练历史数据
     *
     * @param data
     */
    private void doPracticeHistory(byte[] data) {
        ULog.w(TAG, "-----doPracticeHistory-----data = " + getArrayString(data));

    }

    private boolean isStarted = false;
    private int curRow = 0;

    private String getFormatNumber(int number) {
        String result = String.valueOf(number);
        if (result.length() < 2) {
            result = "0" + result;
        }
        return result;
    }


    /**
     * 处理返回数据
     *
     * @param data
     */
    private void doOnFF(byte[] data) {
        int cmdCode = data[2] & 0xff;
        switch (cmdCode) {
            case 0x01://设备请求app下发同步时钟
                ULog.i(TAG, "-----doOnFF--------to do onRequestSyncClock");
                onRequestSyncClock(data);
                break;
            case 0x02://返回信息
                ULog.i(TAG, "-----doOnFF-----to do onReturnMessage");
                onReturnMessage(data);
                break;
            case 0xff://出错
                ULog.i(TAG, "-----doOnFF------to do doError");
                doError(data);
                break;

        }
    }

    /**
     * 处理动态测量数据
     *
     * @param data
     */
    private void onMeasuring(byte[] data) {
        int result = data[1] & 0xff;
        if (measureResultCallback != null) {
            measureResultCallback.onMeasuring(result);
        }
    }


    /**
     * 处理动态测量结果
     *
     * @param data
     */
    private void doMeasureResult(byte[] data) {
        long measureTime = System.currentTimeMillis();
        if (measureTime - preMeasureTime < 56 * 1000) {
            return;
        }

        if (data.length > 8) {
            /***舒张压***/
            int systolicPressure = data[2] & 0xff;
            /***收缩压***/
            int diastolicPressure = data[4] & 0xff;
            /***脉搏***/
            int pulse = data[8] & 0xff;

            IctResult result = new IctResult();
            result.setDiastolicPressure(diastolicPressure);
            result.setSystolicPressure(systolicPressure);
            result.setPulse(pulse);

            preMeasureTime = measureTime;

            result.setMeasureTime(measureTime);
            result.setMeasureTimeStr(getMeasureTimeStr(measureTime));

            if (measureResultCallback != null) {
                measureResultCallback.onReceiveResult(result);
            }
            if (mInternalChannel != null) {
                mInternalChannel.sendCommnd(IctCommand.RECEIVED);
            }
//        stopDeviceSend();
        }
    }

    /**
     * 同步时钟请求
     *
     * @param data
     */
    private void onRequestSyncClock(byte[] data) {
        if (mInternalChannel != null) {
            mInternalChannel.sendCommnd(IctCommand.SYNC_CLOCK);
        }

    }

    /**
     * 处理ICT错误
     *
     * @param data
     */
    private void doError(byte[] data) {
        int errCode = data[3] & 0xff;
        IctError error = null;
        switch (errCode) {
            case 0x00://ICT训练历史记录删除成功
//                if (mOnNoPracticeHistoryDataListener != null) {
//                    mOnNoPracticeHistoryDataListener.onNoPracticeHistoryData();
//                }
                break;
            case 0x01://传感器震荡异常
                error = IctError.SENSOR_EER;
                break;
            case 0x02://检测不到足够的心跳或算不出血压，提示用户重新测量
            case 0x03://测量结果异常
            case 0x04://测量结果异常或压力超过上限 ，提示用户重新测量
                error = IctError.ABNORMAL_RESULT;
                break;
            case 0x05://袖带过松或漏气(10秒内加压不到30mmHg)，提示用户检查臂带并重新邦好
                error = IctError.CUFF_LOOSE_OR_LEAKAGE;
                break;
            case 0x06://电池电量过低，提示用户更换电池
                error = IctError.BATTERY_LOW;
                break;
            case 0x07://其他错误
                error = IctError.OTHER_ERR;
                break;
        }
        if (mErrorCallback != null && error != null) {
            mErrorCallback.onIctErr(error);
        }
    }

    /**
     * 返回信息
     *
     * @param data
     */
    private void onReturnMessage(byte[] data) {
        if (data.length > 3) {
            int infoCode = data[3] & 0xff;
            switch (infoCode) {
                case 0x01: //设置成功
                    ULog.i(TAG, "--doError-------setting success!---------");
                    break;
                case 0x02: //设置失败
                    ULog.i(TAG, "--doError-------setting failed---------");
                    break;
                case 0x03: //无历史数据
                    ULog.i(TAG, "--doError-------no history data---------");
                    break;
            }
        }
    }


    @Override
    public void onRelease() {
        super.onRelease();


    }
}
